<template>
  <div class="user-add">
    <div class="page-header">
      <h2>添加用户</h2>
      <p>创建新的系统用户</p>
    </div>

    <div class="add-form-container">
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="120px" class="user-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="userForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password
                clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="isActive">
              <el-radio-group v-model="userForm.isActive">
                <el-radio :value="true">启用</el-radio>
                <el-radio :value="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="分配角色" prop="roleids">
          <el-select v-model="userForm.roleids" placeholder="请选择角色" style="width: 100%" multiple>
            <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            创建用户
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useRoleStore } from '@/stores/role'
import { usernameRules,passwordRules,emailRules } from '@/utils/validationRules'
const router = useRouter()
const useroleStore=useRoleStore()
const userFormRef = ref()
const loading = ref(false)
const useStore = useUserStore()

// 角色列表
const roleList = ref([])

// 表单数据
const userForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  isActive: true,
  roleids: [],
})

// 验证规则
const userRules = {
  username:usernameRules,
  email:emailRules,
  password: passwordRules,
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  roles: [
    { required: true, message: '请至少选择一个角色', trigger: 'change' }
  ]
}

// 方法
const loadRoles = async () => {
  try {
    // 模拟API调用获取角色列表
    const response = await useroleStore.getRoles();
    console.log(response.roles);
    
    await new Promise(resolve => setTimeout(resolve, 300))
    roleList.value = response.roles; // 假设后端返回的角色列表在 response 中
    console.log(roleList.value);
    
    // 实际情况下这里应该是API请求
    console.log('角色列表加载完成')
  } catch (error) {
    ElMessage.error('加载角色列表失败')
  }
}
//添加用户√
const handleSubmit = async () => {
  try {
    // 表单验证
    await userFormRef.value.validate()

    loading.value = true

    // 调用后端 API 创建用户
    const response = await useStore.adduser(userForm)
    console.log(response)

    await new Promise(resolve => setTimeout(resolve, 1500))
    ElMessage.success('用户创建成功')

    // 跳转到用户列表
    router.push('/users/list')

  } catch (error) {
    if (error) {
      ElMessage.error('用户名或邮箱已存在')
    }
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  userFormRef.value.resetFields()
}

const handleCancel = () => {
  router.push('/users/list')
}

// 生命周期
onMounted(() => {
  loadRoles()
})
</script>

<style scoped>
.user-add {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 5px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.add-form-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-form {
  max-width: 800px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-textarea) {
  width: 100%;
}
</style>
